using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using resharperupdate.core.dto;

namespace resharperupdate.core.services.impl
{
    public class UpdaterTask : IUpdaterTask
    {
        private readonly IRegistryLookup registry_lookup;
        private readonly IDownloader downloader;
        private readonly INightlyBuildParser nightly_build_parser;
        private readonly IProductVersionParser version_parser;

        public UpdaterTask() : this(new RegistryLookup(),new Downloader(), new NightlyBuildParser(), new ProductVersionParser())
        {
        }

        public UpdaterTask(IRegistryLookup registry_lookup, IDownloader downloader,
                           INightlyBuildParser nightly_build_parser, IProductVersionParser version_parser)
        {
            this.registry_lookup = registry_lookup;
            this.downloader = downloader;
            this.nightly_build_parser = nightly_build_parser;
            this.version_parser = version_parser;
        }

        public bool is_update_available()
        {
            return latest_version().Installed == false;
        }

        public IBuild latest_version()
        {
            var html = downloader.nightly_html();
            var build = nightly_build_parser.parse(html);
            try
            {
                var version = registry_lookup.version();
                var build_number = version_parser.build(version);
                if (build_number == build.Number)
                    build.Installed = true;
            }
            catch(DataException dex)
            {
                //Resharper 4.5 isn't installed
            }
            return build;
        }

        public IList<IBuild> available_builds()
        {
            var builds = new List<IBuild>();
            var html = downloader.nightly_html();
            int installed_version = 0;

            try
            {
                var version = registry_lookup.version();
                installed_version = version_parser.build(version);
            }
            catch (DataException dex)
            {
                //Reshaper 4.5 isn't installed
            }

            foreach (var build in nightly_build_parser.for_list(html))
            {
                if (installed_version == build.Number)
                    build.Installed = true;
                builds.Add(build);
            }
            return builds;
        }
    }
}